<template>
  <view class="page-container">
    <!-- 顶部统计区域 -->
    <view class="stats-container bg-primary">
      <view class="stats-item">
        <text class="stats-label">当前余额(元)</text>
        <text class="stats-value">{{ state.balance.toFixed(2) }}</text>
        <button class="withdraw-btn" @tap="handleWithdraw">提现</button>
      </view>
      
      <view class="divider"></view>
      
      <view class="stats-item">
        <view class="stats-right-item">
          <text class="stats-label">累计收入</text>
          <text class="stats-value text-green">{{ state.totalIncome.toFixed(2) }}</text>
        </view>
        <view class="stats-right-item">
          <text class="stats-label">累计提现</text>
          <text class="stats-value">{{ state.totalWithdraw.toFixed(2) }}</text>
        </view>
      </view>
    </view>

    <!-- 收支明细区域 -->
    <view class="detail-container">
      <!-- 日期选择 -->
      <view class="filter-section">
        <picker 
          mode="date" 
          fields="month" 
          :value="state.selectedDate"
          @change="handleDateChange"
        >
          <view class="date-picker">
            <uni-icons type="calendar" size="18" color="#333" />
            <text class="date-text">{{ state.selectedDate }}</text>
            <uni-icons type="arrowdown" size="14" color="#666" />
          </view>
        </picker>
      </view>

      <!-- 明细列表 -->
      <scroll-view 
        scroll-y 
        class="record-list"
        refresher-enabled
        @refresherrefresh="onRefresh"
      >
        <view 
          v-for="(record, index) in filteredRecords" 
          :key="index"
          class="record-card"
        >
          <view class="card-header">
            <view class="record-type">
              <uni-icons 
                :type="record.type === 'verification' ? 'shop' : 'wallet'" 
                size="20" 
                :color="record.type === 'verification' ? '#52c41a' : '#1890ff'"
              />
              <text class="type-text">{{ record.type === 'verification' ? '服务收入' : '提现' }}</text>
            </view>
            <text class="record-amount" :class="record.type === 'verification' ? 'text-green' : 'text-red'">
                {{ record.type === 'verification' ? '+' : '-' }}{{ Math.abs(record.amount).toFixed(2) }}
            </text>
          </view>
          
          <view class="card-body">
            <text class="service-name">{{ record.name }}</text>
            <text class="record-time">{{ formatDateTime(record.recordTime) }}</text>
          </view>
        </view>

        <uni-load-more :status="state.loading ? 'loading' : 'noMore'" />
      </scroll-view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { onPullDownRefresh } from '@dcloudio/uni-app'
import request from '../../utils/request'

// 工具函数
const formatDateTime = (timestamp) => {
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${pad(date.getMonth()+1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}`
}

const pad = (n) => n.toString().padStart(2, '0')

// 状态管理
const state = reactive({
  balance: 0,
  totalIncome: 0,
  totalWithdraw: 0,
  selectedDate: '2024-03',
  records: [],
  loading: false
})

// 计算属性（根据类型分类统计）
const filteredRecords = computed(() => {
  return state.records.filter(item => {
    const recordDate = new Date(item.recordTime)
    const [year, month] = state.selectedDate.split('-')
    return recordDate.getFullYear() == year && 
           (recordDate.getMonth() + 1) == month
  })
})

const initDate = () => {
  const now = new Date()
  state.selectedDate = `${now.getFullYear()}-${pad(now.getMonth()+1)}`
}


// 生命周期
onMounted(() => {
  initDate()
  loadData()
})

// 数据加载
const loadData = () => {
  state.loading = true
  
  request({
    url: `/serviceItem/incomeExpense/1`,
    method: 'get',
  }).then(res => {
    console.log('收支记录请求成功:', res)
    if (res.code === 200 && res.data) {
      // 处理统计数据
      const income = res.data
        .filter(item => item.type === 'verification')
        .reduce((sum, item) => sum + item.amount, 0)
      
      const withdraw = res.data
        .filter(item => item.type === 'withdrawal')
        .reduce((sum, item) => sum + item.amount, 0) // 这里已经是负数
      
      state.balance = income + withdraw // 自动处理正负相加
      
      state.totalIncome = res.data
        .filter(item => item.type === 'verification')
        .reduce((sum, item) => sum + item.amount, 0)
      
      state.totalWithdraw = res.data
        .filter(item => item.type === 'withdrawal')
        .reduce((sum, item) => sum + Math.abs(item.amount), 0)
      
      // 转换时间格式
      state.records = res.data.map(item => ({
        ...item,
        recordTime: item.recordTime ? new Date(item.recordTime).getTime() : Date.now()
      }))
      
      console.log('更新后的收支记录:', state.records)
    }
  }).catch(err => {
    console.error('收支记录请求失败:', err)
    uni.showToast({
      title: '数据加载失败',
      icon: 'none'
    })
  }).finally(() => {
    state.loading = false
  })
}

// 事件处理
const handleWithdraw = () => {
  uni.navigateTo({
    url: `/pages/withdraw/withdraw?balance=${state.balance}`
  })
}

const handleDateChange = (e) => {
  state.selectedDate = e.detail.value
  loadData()
}

const onRefresh = () => {
  loadData()
  setTimeout(() => {
    uni.stopPullDownRefresh()
  }, 1000)
}
</script>

<style lang="scss" scoped>
.page-container {
  background: #f5f5f5;
  min-height: 100vh;
}

.stats-container {
  padding: 40rpx 32rpx;
  display: flex;
  align-items: center;
  border-radius: 0 0 40rpx 40rpx;
  box-shadow: 0 8rpx 20rpx rgba(24, 144, 255, 0.15);

  .stats-item {
    flex: 1;
    padding: 0 32rpx;
  }

  .stats-label {
    display: block;
    font-size: 28rpx;
    color: rgba(255,255,255,0.9);
    margin-bottom: 12rpx;
  }

  .stats-value {
    font-size: 48rpx;
    font-weight: 600;
    color: #fff;
  }

  .divider {
    width: 2rpx;
    height: 120rpx;
    background: rgba(255,255,255,0.3);
  }

  .withdraw-btn {
    margin-top: 32rpx;
    height: 64rpx;
    line-height: 64rpx;
    font-size: 28rpx;
    background: rgba(255,255,255,0.15);
    border-radius: 48rpx;
    color: #fff;
    &::after { border: none; }
  }
}

.detail-container {
  padding: 32rpx;
}

.filter-section {
  margin-bottom: 24rpx;
  
  .date-picker {
    display: inline-flex;
    align-items: center;
    padding: 16rpx 24rpx;
    background: #fff;
    border-radius: 8rpx;
    box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
    
    .date-text {
      margin: 0 12rpx;
      font-size: 28rpx;
      color: #333;
    }
  }
}

.record-list {
  height: calc(100vh - 480rpx);
}

.record-card {
  background: #fff;
  padding: 32rpx;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
  }
  
  .record-type {
    display: flex;
    align-items: center;
    
    .type-text {
      margin-left: 12rpx;
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .record-amount {
    font-size: 36rpx;
    font-weight: 600;
  }
  
  .card-body {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .service-name {
      color: #333;
      font-size: 28rpx;
    }
    
    .record-time {
      color: #999;
      font-size: 24rpx;
    }
  }
}

.text-green { color: #52c41a; }
.text-red { color: #ff4d4f; }
.bg-primary { background: #1890ff; }
</style>